<!--
 * @Author: zhangjingyu
 * @Date: 2020-10-22 19:30:00
 * @LastEditors: zhangjingyu
 * @LastEditTime: 2021-05-11 11:31:39
 * @FilePath: \vprisk10.14\src\views\SystemMange\userManage.vue
 * @Description: 用户管理
-->

<template>
  <!-- 用户管理页面 -->
  <div>
    <upper-template
      @search="(searchForm.page = 1), searchFunc()"
      @clear="searchClear"
      :exportIcon="!inUse"
      :importIcon="!inUse"
    >
      <!-- 操作按钮区 -->
      <template v-if="inUse == false" slot="buttonArea">
        <el-button type="normal" @click="addFunc">新增</el-button>
        <el-button type="normal" @click="editFunc">编辑</el-button>
        <el-button type="normal" @click="unlock(0)">锁定</el-button>
        <el-button type="normal" @click="unlock(1)">解锁</el-button>
        <el-button type="normal" @click="writeOff">注销</el-button>
        <el-button type="normal" @click="authorization('role')"
          >角色授权</el-button
        >
        <!-- <el-button type="normal" @click="authorization('pro')" v-if="tennatId"
          >配置工程</el-button
        > -->
      </template>
        <!-- 导出操作区域 -->
      <div slot="exportArea">
        <el-button @click="exportExcel('userExport')">导出用户</el-button>
      </div>
        <!-- 导入操作区域 -->
      <div slot="importArea">
        <el-upload
          accept=".xls, .xlsx"
          ref="upload"
          :multiple="false"
          :before-upload="beforeUpload"
          :show-file-list="false"
          action
          :limit="1"
          :http-request="uploadFile"
        >
          <el-button>导入用户</el-button>
        </el-upload>
        <!-- <el-upload
                    style="margin:10px 5px"
                    accept=".xls, .xlsx"
                    ref="roleUpload"
                    :multiple="false"
                    :before-upload="beforeUpload"
                    :show-file-list="false"
                    action
                    :limit="1"
                    :http-request="roleUploadFile"
                  >
                    <el-button>导入角色</el-button>
                  </el-upload> -->
      </div>
      <!-- 搜索区域 -->
      <div slot="searchArea">
        <el-form
          :model="searchForm"
          ref="searchForm"
          label-width="90px"
          label-position="left"
          size="mini"
        >
          <el-form-item label="姓　　名：">
            <el-input
              v-model.trim="searchForm.realName"
              style="width: 150px"
              @keydown.enter.native="searchFunc()"
            ></el-input>
          </el-form-item>
          <el-form-item label="用 户 名：" prop="userName">
            <el-input
              v-model.trim="searchForm.userName"
              style="width: 150px"
              @keydown.enter.native="searchFunc()"
            ></el-input>
          </el-form-item>
          <el-form-item label="所属机构：" prop="orgId">
            <el-tooltip
              :content="searchOrgTip"
              :disabled="!searchOrgTip"
              placement="right-end"
              class="item"
            >
              <el-cascader
                clearable
                filterable
                :options="orgList"
                v-model="searchForm.orgId"
                :props="{
                  checkStrictly: true,
                  emitPath: false,
                  value: 'orgId',
                  label: 'orgName'
                }"
                :show-all-levels="false"
                style="width: 150px"
                ref="searchOrgTree"
                @change="searchOrgHandle"
              ></el-cascader>
            </el-tooltip>
          </el-form-item>
          <el-form-item label="状　　态：" prop="useFlag">
            <el-select
              v-model="searchForm.useFlag"
              placeholder="请选择"
              style="width: 150px"
            >
              <el-option label="启用" value="1"></el-option>
              <el-option label="锁定" value="0"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="角　　色：" prop="roleName">
            <el-input
              v-model="searchForm.roleName"
              style="width: 150px"
            ></el-input>
          </el-form-item>
        </el-form>
      </div>
      <!-- 列表显示隐藏操作区 -->
      <div slot="columnHide">
        <el-checkbox-group v-model="checkList">
          <el-checkbox
            v-for="item in textData"
            :label="item.label"
            :key="item.prop"
            >{{ item.label }}
          </el-checkbox>
        </el-checkbox-group>
      </div>
    </upper-template>
    <!-- 表格区 -->
    <el-table
      ref="multipleTable"
      :data="tableData"
      style="width: 100%"
      @row-click="multipleTableRowClick"
    >
      <el-table-column
        width="55"
        type="selection"
        
      ></el-table-column>
      <el-table-column
        prop="userName"
        label="用户名"
        v-if="columnState[0]"
        show-overflow-tooltip
        align="left"
      >
      </el-table-column>
      <el-table-column
        prop="realName"
        label="用户姓名"
        sortable
        show-overflow-tooltip
        v-if="columnState[1]"
        align="left"
      >
      </el-table-column>
      <el-table-column
        prop="org.orgName"
        label="机构"
        sortable
        show-overflow-tooltip
        v-if="columnState[2]"
        align="left"
      >
      </el-table-column>
      <el-table-column
        prop="useFlag"
        label="状态"
        v-if="columnState[3]"
        :filter-method="(val, row) => row.useFlag === val"
        :filters="[
          { text: '启用', value: '1' },
          { text: '锁定', value: '0' }
        ]"
        align="left"
      >
        <template slot-scope="scope">
          <div v-if="scope.row.useFlag == '1'">
            <i class="startState"></i>启用
          </div>
          <div v-else-if="scope.row.useFlag == '0'">
            <i class="unStartState"></i>锁定
          </div>
          <div v-else>
            {{ scope.row.useFlag }}
          </div>
        </template>
      </el-table-column>
      <el-table-column
        prop="roles"
        label="授权角色"
        sortable
        v-if="columnState[4]"
        align="left"
        show-overflow-tooltip
      >
        <template slot-scope="scope">
          {{ scope.row.roles.map(v => v.roleName).toString() }}
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      @refresh="searchFunc"
      :current-page="searchForm.page"
      :page-size="searchForm.size"
      :total="total"
    ></pagination>
    <!-- 新增弹窗 -->
    <el-dialog
      v-dialogDrag
      :title="saveTitles[saveFlg - 1]"
      :visible.sync="addOrEdit"
      width="514px"
    >
      <el-form
        :model="saveForm"
        ref="saveForm"
        label-width="97px"
        label-position="left"
        :rules="saveFormRules"
      >
        <el-row>
          <el-col :span="24">
            <el-form-item label="用户名：" prop="userName">
              <el-input
                v-model.trim="saveForm.userName"
                maxlength="40"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="用户姓名：" prop="realName">
              <el-input
                v-model.trim="saveForm.realName"
                maxlength="50"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="用户密码：" prop="password">
              <el-input
                v-model.trim="saveForm.password"
                type="password"
                maxlength="40"
                @blur="passwordChange"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24" style="margin-top: 5px">
            <el-form-item label="确认密码：" prop="passwordStr">
              <el-input
                v-model.trim="saveForm.passwordStr"
                type="password"
                maxlength="40"
                @blur="passwordChange"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="所属机构：" prop="orgId">
              <el-tooltip
                :content="saveOrgTip"
                :disabled="!saveOrgTip"
                placement="top"
                class="item"
              >
                <el-cascader
                  clearable
                  filterable
                  :options="orgList"
                  v-model="saveForm.orgId"
                  :props="{
                    checkStrictly: true,
                    emitPath: false,
                    expendTrigger: 'hover',
                    value: 'orgId',
                    label: 'orgName'
                  }"
                  :show-all-levels="false"
                  ref="saveOrgTree"
                  style="width: 100%"
                  @change="checkFormOrg"
                >
                </el-cascader>
              </el-tooltip>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="用户状态：" prop="useFlag">
              <el-select
                v-model="saveForm.useFlag"
                disabled
                style="width: 100%"
              >
                <el-option value="1" label="启用"></el-option>
                <el-option value="0" label="撤销"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="员工编号：" prop="empNo">
              <el-input v-model.trim="saveForm.empNo" maxlength="40"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="身份证号：" prop="idcard">
              <el-input
                v-model.trim="saveForm.idcard"
                maxlength="40"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="办公电话：" prop="officePhone">
              <el-input
                v-model.trim="saveForm.officePhone"
                maxlength="40"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="移动电话：" prop="mobilePhone">
              <el-input
                v-model.trim="saveForm.mobilePhone"
                maxlength="40"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="家庭电话：" prop="famliyPhone">
              <el-input
                v-model.trim="saveForm.famliyPhone"
                maxlength="40"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="邮箱地址：" prop="email">
              <el-input v-model.trim="saveForm.email" maxlength="40"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="saveFunc" v-if="saveFlg != 3">确 定</el-button>
        <el-button @click="addOrEdit = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 授权角色和授权工程弹窗 -->
    <!-- 配置弹窗 -->
    <el-dialog
      :title="
        '为' + userName + '授权' + (rightButtonFlag == 'pro' ? '工程' : '角色')
      "
      v-dialogDrag
      :visible.sync="isConfig"
      width="40%"
    >
      <!-- 角色授权table -->
      <el-table
        ref="roleTable"
        :data="tableDataRole"
        v-if="rightButtonFlag == 'role'"
        style="width: 100%"
        class="isRightTable"
        @row-click="
          row => {
            this.$refs.roleTable.toggleRowSelection(row);
          }
        "
      >
        <el-table-column
          width="55"
          type="selection"
          
        ></el-table-column>
        <el-table-column prop="roleCode" label="角色编号"></el-table-column>
        <el-table-column prop="roleName" label="角色名称"></el-table-column>
      </el-table>

      <!-- 工程授权table -->
      <el-table
        ref="proTable"
        :data="tableDataPro"
        v-if="rightButtonFlag == 'pro'"
        style="width: 100%"
        class="isRightTable"
        @row-click="rowClickPro"
      >
        <el-table-column
          width="55"
          type="selection"
          
        ></el-table-column>
        <el-table-column prop="projectName" label="工程名称 "></el-table-column>
      </el-table>
      <div
        slot="footer"
        class="dialog-footer"
        style="display: flex; align-item: center; justify-content: center"
      >
        <el-button style="margin: 10px 5px" @click="saveRoleOrPro"
          >保存</el-button
        >
      </div>
      <pagination
        @size-change="handleSizeChangePro"
        @current-change="handleCurrentChangePro"
        @refresh="queryAllPro"
        :current-page="searchFormPro.page"
        :page-size="searchFormPro.size"
        :total="totalPro"
      ></pagination>
    </el-dialog>
  </div>
</template>

<script>
import { systemManage } from "@/api/index";
import sm4 from "@/lib/gmsm4/index";
export default {
  data() {
    return {
      tennatId: sessionStorage.getItem("tennatId"), //系统管理员身份 无租户id  用户管理无配置工程按钮
      selectionData: [],
      key: "40ca11f573cce61cc28e19998d5bb1c8",
      iv: "31313131313131313131313131313131",
      userName: "",
      addOrEdit: false, // 新增/编辑/查看弹窗
      saveFlg: 1, // 1:新增，2：编辑，3查看,
      rightButtonFlag: "role", // 区分角色授权（role）和工程授权（pro）
      isConfig: false,
      saveTitles: ["添加用户信息", "编辑用户信息"],
      // 机构树
      orgList: [],
      // 历史密码密文串
      hisPwd: "",
      clickRow: {},
      // search机构树悬停提示
      searchOrgTip: "",
      // save表单机构树悬停提示
      saveOrgTip: "",
      searchForm: {
        page: 1,
        size: 15
      },
      searchFormPro: {
        page: 1,
        size: 15,
        projectName: "",
        projectId: ""
      },
      total: 0,
      totalPro: 0,
      saveForm: {
        operateType: "2",
        userId: "",
        userName: "",
        realName: "",
        password: "",
        passwordStr: "",
        orgId: "organ1uuid1",
        useFlag: "",
        empNo: "",
        idcard: "",
        officePhone: "",
        mobilePhone: "",
        famliyPhone: "",
        email: ""
      },
      saveFormRules: {
        userName: [
          {
            required: true,
            message: "该输入项为必输项",
            trigger: "blur"
          },
          {
            pattern: /^[0-9a-zA-Z_]{3,16}$/,
            message: "只能输入3-16位的英文字母、数字、下划线",
            trigger: "blur"
          },
          { validator: this.userNameValid, trigger: "blur" }
        ],
        realName: [
          {
            required: true,
            message: "该输入项为必输项",
            trigger: "blur"
          }
        ],
        password: [
          {
            required: true,
            message: "该输入项为必输项",
            trigger: "blur"
          },
          { validator: this.validFirtPassword, trigger: "blur" }
        ],
        passwordStr: [
          {
            required: true,
            message: "该输入项为必输项",
            trigger: "blur"
          },
          { validator: this.validPassword, trigger: "blur" }
        ],
        orgId: [
          {
            required: true,
            message: "该输入项为必输项",
            trigger: "blur"
          }
        ],
        status: [
          {
            required: true,
            message: "该输入项为必输项",
            trigger: "blur"
          }
        ],
        empNo: [
          {
            pattern: /^[0-9a-zA-Z_]{0,50}$/,
            message: "只能输入0-50位的英文字母、数字、下划线",
            trigger: "blur"
          }
        ],
        idcard: [
          {
            pattern: /^[1-9]\d{5}(18|19|20|(3\d))\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/,
            message: "请输入有效的身份证号码",
            trigger: "blur"
          }
        ],
        officePhone: [
          {
            pattern: /^0\d{2,3}-[1-9]\d{6,7}$/,
            message: "请按正确格式输入电话号码（区号-电话号码）",
            trigger: "blur"
          }
        ],
        famliyPhone: [
          {
            pattern: /^0\d{2,3}-[1-9]\d{6,7}$/,
            message: "请按正确格式输入电话号码（区号-电话号码）",
            trigger: "blur"
          }
        ],
        mobilePhone: [
          {
            pattern: /^(13[0-9]|14[5|7]|15[0|1|2|3|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d{8}$/,
            message: "请按正确格式输入手机号",
            trigger: "blur"
          }
        ]
      },
      checkList: [],
      // 完整表头字段&&列属性配置
      textData: [
        { prop: "userName", label: "用户名", align: "left" },
        { prop: "realName", label: "用户姓名", sortable: true },
        { prop: "orgName", label: "机构 ", sortable: true },
        {
          prop: "useFlag",
          label: "状态"
        },
        // {
        //   prop: "project.projectName",
        //   label: "授权工程 ",
        //   sortable: true,
        // },
        { prop: "role[0].roleName", label: "授权角色", sortable: true }
      ],
      // 获取table的数据
      tableData: [],
      tableDataPro: [
      ],
      tableDataRole: [],
      notContainsUsername: false
    };
  },
  props: {
    orgId: {
      type: String,
      default: ""
    },
    inUse: {
      type: Boolean,
      default: false
    }
  },
  created() {
    this.checkListInit();
    this.getOrgList();
    this.getPasswordRlue({});
    this.isContainsUsername();
    console.log(this.tableData, "模拟数据");
  },
  computed: {
    columnState() {
      console.log(this.checkList);
      let arr = [],
        arr1 = this.textData,
        arr2 = this.checkList;
      for (let i = 0; i < arr1.length; i++) {
        let flg = false;
        for (let j = 0; j < arr2.length; j++) {
          if (arr1[i].label === arr2[j]) {
            flg = true;
          }
        }
        arr.push(flg);
      }
      return arr;
    },
    // 展示字段
    showData() {
      let arr = this.textData.map(v => {
        return v.label;
      });
      let valArr = [],
        showData = [];
      // 选中的字段排序
      arr.forEach(element => {
        let flag = false;
        this.checkList.forEach(e => {
          if (e == element) {
            flag = true;
          }
        });
        if (flag) {
          valArr.push(element);
        }
      });
      // 控制表列隐藏显示
      for (let i = 0; i < this.checkList.length; i++) {
        for (let j = 0; j < this.textData.length; j++) {
          if (this.textData[j].label == valArr[i]) {
            let item = { ...this.textData[j] };
            showData.push(item);
          }
        }
      }
      return showData;
    }
  },
  mounted() {
    // this.searchFunc();
    this.queryAllRole();
    // this.queryAllPro();
  },
  watch: {
    addOrEdit() {
      // 窗口打开或关闭清除校验结果
      if (this.$refs.saveForm) {
        this.$refs.saveForm.clearValidate();
      }
    }
  },
  methods: {
    rowClickPro(row) {
      if (this.$refs.multipleTable) {
        this.$refs.proTable.clearSelection();
      }
      this.$refs.proTable.toggleRowSelection(row, true);
    },
    // 获取机构数据
    getOrgList() {
      systemManage.getOrganTree().then(res => {
        console.log(res, "机构");
        this.orgList = res;
      });
    },
    // 处理搜索机构框点击选中隐藏,鼠标悬停提示
    searchOrgHandle() {
      this.$refs.searchOrgTree.dropDownVisible = false;
      let node = this.$refs.searchOrgTree.getCheckedNodes();
      if (node.length != 0) {
        this.searchOrgTip = node[0].label;
      } else {
        this.searchOrgTip = "";
      }
    },
    // 处理save表单机构选中事件
    checkFormOrg() {
      let node = this.$refs.saveOrgTree.getCheckedNodes();
      this.$refs.saveOrgTree.dropDownVisible = false; // 隐藏模态框
      console.log(node,'node',node.length,node[0],'node.length')
      if (node[0]) {
        this.saveForm.orgName = node[0].label;
        this.saveOrgTip = node[0].label;
      } else {
        this.saveForm.orgName = "";
        this.saveOrgTip = "";
        this.$message.warning("原机构" +this.saveForm.orgId + "已被停用，请重新选择")
        this.saveForm.orgId=""
      }
    },
    // 上传文件之前的钩子
    beforeUpload(file) {
      let name = file.name;
      let type = name.substring(name.lastIndexOf("."), name.length);
      // console.log(type,"type")
      if (type === ".xls" || type === ".xlsx") {
        return true;
      } else {
        this.$message.warning("只能选择xls或者xlsx格式的文件上传");
        return false;
      }
    },
    // 上传文件
    uploadFile(item) {
      let form = new FormData();
      // 文件对象
      form.append("excelFile ", item.file);
      // console.log('导入文件',JSON.stringify(form) ,item)
      // 发送请求
      systemManage
        .userImport(form)
        .then(res => {
          if (res.code == 200) {
            this.$message.success("导入成功");
            this.searchFunc();
          } else {
            this.$message.error(res.message);
          }
          this.$refs.upload.clearFiles();
        })
        .catch(err => {
          this.$refs.upload.clearFiles();
        });
    },
    //excel导出
    exportExcel(api) {
      let data = null;
      if (api == "userExport") {
        data = { ...this.searchForm };
      }
      if (api == "userExpUserRole") {
        let userIds = this.$refs.multipleTable.selection;
        if (userIds.length > 0) {
          data = {
            userIds
          };
        } else {
          data = { ...this.searchForm };
        }
      }
      systemManage[api](data)
        .then(res => {
          console.log(res);
          if (res.status == 200) {
            console.log(decodeURI(res.headers["content-disposition"]));
            var filename = decodeURI(res.headers["content-disposition"]).split(
              "="
            )[1];
            let contenttype =
              filename.substring(filename.lastIndexOf("."), filename.length) ===
              "xlsx"
                ? "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8"
                : "application/vnd.ms-excel;charset=utf-8";

            var blob = new Blob([res.data], {
              type: contenttype
            });
            if (window.navigator.msSaveOrOpenBlob) {
              navigator.msSaveBlob(blob, filename);
            } else {
              var downloadElement = document.createElement("a");
              var href = window.URL.createObjectURL(blob); //创建下载的链接
              downloadElement.href = href;
              downloadElement.download = filename; //下载后文件名
              document.body.appendChild(downloadElement);
              downloadElement.click(); //点击下载
              document.body.removeChild(downloadElement); //下载完成移除元素
              window.URL.revokeObjectURL(href); //释放掉blob对象
            }
            this.$message.success("导出成功");
          } else {
            this.$message.error(res.message || "获取失败");
          }
        })
        .catch(() => {});
    },
    //角色导入
    roleUploadFile(item) {
      let form = new FormData();
      // 文件对象
      form.append("excelFile ", item.file);
      // 发送请求
      systemManage
        .userImpUserRole(form)
        .then(res => {
          if (res.code == 200) {
            this.$message.success("导入成功");
            this.searchFunc();
          } else {
            this.$message.error(res.message);
          }
          this.$refs.roleUpload.clearFiles();
        })
        .catch(err => {
          this.$refs.roleUpload.clearFiles();
        });
    },
    // 密码校验
    validFirtPassword(rule, value, callback) {
      console.log(this.saveForm.userName, this.notContainsUsername);
      // 是否有不能包含用户名的设置
      if (
        this.saveForm.password != "password" &&
        this.saveForm.userName.length > 0 &&
        this.notContainsUsername === true &&
        this.saveForm.password.indexOf(this.saveForm.userName) != -1
      ) {
        callback(new Error("密码中不能包含用户名"));
        return;
      }
      // --------以下在新增时不校验
      if (this.saveFlg == 1) {
        callback();
        return;
      }
      // 密码校验是否与前？次重复
      let data = {
        hisPwd: this.hisPwd,
        password: this.saveForm.password
      };
      systemManage.passwardRepeatHis(data).then(res => {
        if (res.code == 200) {
          callback();
        } else {
          callback(new Error(res.message || "格式不符合密码策略"));
        }
      });
    },
    // 密码校验是否设置了不包含用户名
    isContainsUsername(rule, value, callback) {
      systemManage.findDefPasswordRule().then(res => {
        if (res.code == 200) {
          this.notContainsUsername = res.data.notContainsUsername == "1";
        }
      });
    },
    // 密码策略获取
    getPasswordRlue(data) {
      systemManage.passwardValidRule(data).then(res => {
        let list = res.data.rules;
        // 前n次旧密码
        if (this.saveFlg != 1) {
          this.hisPwd = res.data.str_not_his_numbs.rule;
        }
        let passwordRule = [
          {
            required: true,
            message: "该输入项为必输项",
            trigger: "blur"
          },
          { validator: this.validFirtPassword, trigger: "blur" }
        ];
        for (let i = 0; i < list.length; i++) {
          let obj = {
            pattern: eval("/" + list[i].rule + "/"),
            message: list[i].msg,
            trigger: "blur"
          };
          passwordRule.push(obj);
        }
        this.saveFormRules.password = passwordRule;
      });
    },
    // 两个密码校验
    validPassword(rule, value, callback) {
      if (this.saveForm.password === this.saveForm.passwordStr) {
        callback();
      } else {
        callback(new Error("两次输入密码不一致"));
      }
    },
    // 用户名是否重复校验
    userNameValid(rule, value, callback) {
      // 只在新增时校验
      if (this.saveFlg != 1) {
        callback();
        return;
      }
      systemManage.userNameValid({ userName: value }).then(res => {
        if (res.code == 200) {
          callback();
        } else {
          callback(new Error(res.message || "用户名已存在"));
        }
      });
    },
    checkListInit() {
      this.checkList = this.textData.map(v => {
        return v.label;
      });
    },
    // 查询
    searchFunc() {
      let data = this.searchForm;
      if (this.orgId) {
        this.searchForm.orgId = this.orgId;
      }
      console.log(data);
      systemManage
        .queryUser(data)
        .then(res => {
          if (res.code == 200) {
            this.tableData = res.datas.rows;
            this.total = res.datas.total;
            // // 默认传入第一行的数据到右侧，默认为授权角色
            // this.$nextTick(()=>{
            //   this.authorizeFor(this.tableData[0]);
            // })
          }
        })
        .catch(err => {});
    },
    // 查询角色列表
    queryAllRole() {
      systemManage.queryRoles().then(res => {
        if (res.code == 200) {
          this.tableDataRole = res.datas;
          this.searchFunc();
        }
      });
    },
    queryAllPro() {
      systemManage.projectQuery().then(res => {
        if (res.code == 200) {
          this.tableDataPro = res.datas.rows;
          this.totalPro = res.datas.total;
          this.searchFunc();
        }
      });
    },
    searchClear() {
      for (const key in this.searchForm) {
        this.searchForm[key] = "";
      }
      this.searchForm.page = 1;
      this.searchForm.size = 15;
      if (this.orgId) {
        this.searchForm.orgId = this.orgId;
      }
    },
    // 编辑时如果密码被更改，使用密码策略
    passwordChange() {
      if (this.saveFlg == 2 && this.saveFlg != "password") {
        this.getPasswordRlue({
          operateType: "2",
          userId: this.saveForm.userId
        });
      }
    },
    addFunc() {
      this.saveFlg = 1;
      // 新增使用密码策略
      this.getPasswordRlue({ operateType: "1" });

      for (let k in this.saveForm) {
        this.saveForm[k] = "";
      }
      this.saveForm.useFlag = "1";
      this.addOrEdit = true;
      this.$nextTick(() => {
        // 清除校验结果
        this.$refs.saveForm.clearValidate();
      });
    },
    editFunc() {
      this.saveFlg = 2;
      // 编辑默认不使用密码策略，若修改密码会触发密码策略校验
      this.saveFormRules.password = [
        {
          required: true,
          message: "该输入项为必输项",
          trigger: "blur"
        }
      ];
      let selection = this.$refs.multipleTable.selection;
      if (selection.length != 1) {
        return this.$message.warning("请选择一条数据进行修改");
      }
      let row = selection[0];
      let form = { ...row };
      this.saveForm.userId = form.userId;
      this.saveForm.userName = form.userName;
      this.saveForm.realName = form.realName;
      this.saveForm.password = "password";
      this.saveForm.passwordStr = "password";
      this.saveForm.orgId = form.org.orgId;
      this.saveForm.orgName = form.org.orgName;
      this.saveForm.useFlag = form.useFlag;
      this.saveForm.empNo = form.empNo;
      this.saveForm.idcard = form.idcard;
      this.saveForm.officePhone = form.officePhone;
      this.saveForm.mobilePhone = form.mobilePhone;
      this.saveForm.famliyPhone = form.famliyPhone;
      this.saveForm.email = form.email;
      this.addOrEdit = true;
      this.$nextTick(()=>{
      this.checkFormOrg()
      })
    },
    saveFunc() {
      this.$refs["saveForm"].validate(valid => {
        if (valid) {
          //加密
          let form = JSON.parse(JSON.stringify(this.saveForm));
          form.password =
            form.password == "password"
              ? "password"
              : sm4.encryptWithECB(this.key, this.saveForm.password);
          form.passwordStr =
            form.passwordStr == "password"
              ? "password"
              : sm4.encryptWithECB(this.key, this.saveForm.passwordStr);
          systemManage
            .saveUser(form)
            .then(res => {
              if (res.code == 200) {
                console.log(res);
                this.$message.success("保存成功");
                this.addOrEdit = false;
                this.searchFunc();
              } else {
                return this.$message.error(res.message);
              }
            })
            .catch(err => {});
        }
      });
    },
    unlock(id) {
      let val = id == 0 ? "锁定" : "解锁";
      let fn = id == 0 ? "userLock" : "userUnlock";
      let selection = this.$refs.multipleTable.selection;
      if (selection.length < 1) {
        return this.$message.warning("请选择要解锁的用户");
      }
      this.$confirm("您确定要" + val + "选择中的用户吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          let ids = selection.map(v => v.userId);
          console.log("参数：", ids);
          systemManage[fn]({ ids: ids })
            .then(res => {
              if (res.code == 200) {
                this.$message.success(val + "成功");
                this.searchFunc();
              }
            })
            .catch(err => {});
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消" + val
          });
        });
    },
    writeOff() {
      let selection = this.$refs.multipleTable.selection;
      if (selection.length < 1) {
        return this.$message.warning("请选择要注销的用户");
      }
      this.$confirm(
        "您确定要注销选中的用户吗，注销后该用户将不能使用，请慎重！",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      )
        .then(() => {
          let ids = selection.map(v => v.userId);
          systemManage.cancelUsing({ ids }).then(res => {
            if (res.code == 200) {
              this.$message.success("注销成功");
              this.searchFunc();
            } else {
              this.$message.error(res.message);
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消注销"
          });
        });
    },
    handleNodeClick() {
      let nodes = this.$refs.caliberConfigTree.getCheckedNodes();
      console.log(nodes);
    },
    caliberProjectNameFormatter(row) {
      return row.caliberProject.caliberProjectName;
    },
    // 回显对沟
    authorizeFor(row) {
      this.clickRow = row;
      if (this.$refs.multipleTable) {
        this.$refs.multipleTable.clearSelection();
      }
      this.$refs.multipleTable.toggleRowSelection(row, true);
      this.userName = row.userName;
      this.$refs.roleTable.clearSelection();
      if (row.roles && row.roles.length != 0) {
        for (let i = 0; i < row.roles.length; i++) {
          for (let j = 0; j < this.tableDataRole.length; j++) {
            if (row.roles[i].roleCode == this.tableDataRole[j].roleCode)
              this.$refs.roleTable.toggleRowSelection(
                this.tableDataRole[j],
                true
              );
          }
        }
      }
    },
    // 工程配置授权
    authorizeForPro(row) {
      if (this.$refs.multipleTable) {
        this.$refs.multipleTable.clearSelection();
      }
      this.$refs.multipleTable.toggleRowSelection(row, true);
      this.userName = row.userName;
      this.$refs.proTable.clearSelection();
      if (row.projects && row.projects.length != 0) {
        for (let i = 0; i < row.projects.length; i++) {
          for (let j = 0; j < this.tableDataPro.length; j++) {
            if (row.projects[i].projectId == this.tableDataPro[j].projectId)
              this.$refs.proTable.toggleRowSelection(
                this.tableDataPro[j],
                true
              );
          }
        }
      }
    },

    // 角色或工程的保存
    saveRoleOrPro() {
      console.log(this.rightButtonFlag);
      if (this.rightButtonFlag == "role") {
        let arr = this.$refs.roleTable.selection,
          roles = [...this.clickRow.roles],
          mgrIds = [],
          mgrCodes = [],
          userAllRoleIds = [];
        arr.forEach(element => {
          mgrIds.push(element.roleId);
          mgrCodes.push(element.roleCode);
        });
        roles.forEach(element => {
          userAllRoleIds.push(element.roleId);
        });
        let data = {
          userId: this.clickRow.userId,
          mgrIds,
          mgrCodes,
          userAllRoleIds
        };
        console.log(data);
        // 保存接口调用
        systemManage.saveMgrRoles(data).then(res => {
          if (res.code == 200) {
            this.$message.success("保存成功");
            this.searchFunc();
            this.isConfig = false;
          } else {
            this.$message.error(res.msg || res.message);
          }
        });
      }
      if (this.rightButtonFlag == "pro") {
        let arr = this.$refs.proTable.selection;
        let ids = arr.map(v => v.projectId);
        let userAllProjectIds = this.selectionData[0].projects.map(
          v => v.projectId
        );
        let data = {
          userId: this.selectionData[0].userId,
          mgrIds: ids,
          userAllProjectIds: userAllProjectIds
        };
        systemManage.saveMgrProjects(data).then(res => {
          if (res.code == 200) {
            this.$message.success("授权工程成功");
            this.isConfig = false;
            this.searchFunc();
          } else {
            this.$message.error(res.message);
          }
        });
      }
    },
    authorization(str) {
      let checked = this.$refs.multipleTable.selection;
      if (checked.length < 1) {
        return this.$message.warning("请选择一条数据");
      } else if (checked.length > 1) {
        return this.$message.warning("只能选择一条数据");
      } else {
        this.selectionData = this.$refs.multipleTable.selection;
        this.rightButtonFlag = str;
        this.isConfig = true;
        this.$nextTick(() => {
          if (str == "role") {
            this.authorizeFor(checked[0]);
          }
          if (str == "pro") {
            this.authorizeForPro(checked[0]);
          }
        });
      }
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.searchForm.size = val;
      this.searchFunc();
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.searchForm.page = val;
      this.searchFunc();
    },
    handleSizeChangePro(val) {
      console.log(`每页 ${val} 条`);
      this.searchFormPro.size = val;
      this.queryAllPro();
    },
    handleCurrentChangePro(val) {
      console.log(`当前页: ${val}`);
      this.searchFormPro.page = val;
      this.queryAllPro();
    },
    multipleTableRowClick(row) {
      this.$refs.multipleTable.clearSelection();
      this.$refs.multipleTable.toggleRowSelection(row, true);
    }
  }
};
</script>

<style lang="scss" scoped>
</style>
<!-- Access-Control-Expose-Headers: Content-Disposition-->